<?php
App::uses('AppModel', 'Model');
/**
 * Service Model
 *
 * @property Case $Case
 */
class Service extends AdminAppModel {

/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'name';


	//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * hasMany associations
 *
 * @var array
 */
	public $hasMany = array(
		'Case' => array(
			'className' => 'Case',
			'foreignKey' => 'service_id',
			'dependent' => false,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'exclusive' => '',
			'finderQuery' => '',
			'counterQuery' => ''
		)
	);

    public $actsAs = array('Containable');

    /**
     * 保存信息
     * @param array $req 用户提交上来的数据
     * @param boolean $isUpdate 是否更新
     * @param array $news 要修改的原始数据
     */
    public function saveService($req, $isUpdate=false, $news=array() )
    {
        debug($req);
        // upload title_img
        $icon = $this->_uploadIcon($req, $isUpdate, $news);

        $data = array(
            'Service' => array(
                'name' => $req['name'],
                'desc' => $req['desc'],
                'priority' => $req['priority'],
                'in_home' => $req['in_home'],
                'icon' => $icon,
                'updated' => time()
            )
        );
        if ($isUpdate) {
            $this->id = $req['id'];
        } else {
            $this->create();
        }
        if (!$this->save($data)) {
            throw new Exception("The data could not be saved.");
        }
    }
    
    /**
     * 处理标题的图片logo
     * @param array $requestData 用户提交上来的数据
     * @param boolean $isUpdate 是否更新
     * @param array $news 要修改的原始数据
     */
    private function _uploadIcon($requestData, $isUpdate=false, $orginData=array())
    {
        if ($isUpdate) {
            $orginImage = $orginData['icon'];
        }
        $uploadFile = $this->upload($requestData['icon'], 'service_icon_', 'upload title img fail!');
        if (empty($uploadFile)) {
            return $orginImage; 
        }
        return $uploadFile;
    }

}
